package com.streamkar.common.config.session;

import com.streamkar.constant.Constants;
import com.streamkar.entity.domain.Account;
import com.streamkar.entity.domain.Agency;
import com.streamkar.entity.domain.Talent;
import com.streamkar.service.AgencyService;
import com.streamkar.service.TalentService;
import com.streamkar.util.AccountLocalCache;
import com.streamkar.util.Cryptos;
import com.streamkar.util.SpringContextUtil;
import com.streamkar.util.ThreadLocals;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

@Component("userSession")
public class UserSession {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserSession.class);

    public Boolean checkSession(HttpServletRequest request) {
        if (request == null || request.getSession() == null) {
            LOGGER.warn("request is null ...");
            return false;
        }

        String originSsoToken = null;
        Cookie ssoCookieCode = WebUtils.getCookie(request, Constants.COOKIE_KEY);
        if (null != ssoCookieCode && StringUtils.isNotBlank(ssoCookieCode.getValue())) {
            originSsoToken = ssoCookieCode.getValue();
            LOGGER.info("get user token from request cookie ,originSsoToken : {} ...", originSsoToken);
        }

        if (StringUtils.isBlank(originSsoToken)) {
            if (StringUtils.isNotBlank(request.getHeader(Constants.USER_TOKEN))) {
                originSsoToken = request.getHeader(Constants.USER_TOKEN);
                LOGGER.info("get user token from request header ,originSsoToken : {} ...", originSsoToken);
            }
        }

        if (StringUtils.isBlank(originSsoToken)) {
            if (StringUtils.isNotBlank(request.getParameter(Constants.USER_TOKEN))) {
                originSsoToken = request.getParameter(Constants.USER_TOKEN);
                LOGGER.info("get user token from request parameter ,originSsoToken : {} ...", originSsoToken);
            }
        }

        if (StringUtils.isBlank(originSsoToken)) {
            LOGGER.info("request cannot find originSsoToken, request need login ...");
            return false;
        }

        String realSsoToken = Cryptos.aesDecrypt(originSsoToken, Constants.TOKEN_KEY);
        if (StringUtils.isBlank(realSsoToken)) {
            LOGGER.info("request originSsoToken is wrong, cannot decrypt ...");
            return false;
        }

        Account account = AccountLocalCache.getCache(NumberUtils.toInt(realSsoToken));
        if (null == account || null == account.getUserId()) {
            LOGGER.info("json to userSession is null ...");
            return false;
        }

        ThreadLocals.put(Constants.USER_TOKEN, account);
        return Boolean.TRUE;
    }

    public Boolean checkMockSession(HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        Account account = new Account();
        if (requestURI.startsWith(Constants.ADMIN_PREFIX)) {
            account.setRole(Constants.TALENT_MANAGER);
            account.setUserId(4000000);
        } else if (requestURI.startsWith(Constants.AGENCY_PREFIX)) {
            AgencyService agencyService = (AgencyService) SpringContextUtil.getBean("agencyServiceImpl");
            Agency agency = agencyService.agencyInfo(11261);
            account.setUserId(11261);
            account.setRole(Constants.AGENCY);
            account.setAccountInfo(agency);
        } else if (requestURI.startsWith(Constants.TALENT_PREFIX)) {
            TalentService talentService = (TalentService) SpringContextUtil.getBean("talentServiceImpl");
            Talent talent = talentService.talentInfo(554294381);
            account.setUserId(554294381);
            account.setRole(Constants.TALENT);
            account.setAccountInfo(talent);
        }
        ThreadLocals.put(Constants.USER_TOKEN, account);
        return Boolean.TRUE;
    }

    public Account getMockAccountSession(HttpServletRequest request) {
        checkMockSession(request);
        Account account = (Account) ThreadLocals.get(Constants.USER_TOKEN);
        return account;
    }

    public Account getAccountSession(HttpServletRequest request) {
        checkSession(request);
        Account account = (Account) ThreadLocals.get(Constants.USER_TOKEN);
        return account;
    }

    public Account getAccountSession() {
        if (ThreadLocals.get(Constants.USER_TOKEN) != null) {
            Account account = (Account) ThreadLocals.get(Constants.USER_TOKEN);
            return account;
        }
        LOGGER.info("get user sessiom from threadlocal is null ...");
        return null;
    }

    public Integer getUserId() {
        if (ThreadLocals.get(Constants.USER_TOKEN) != null) {
            Account account = (Account) ThreadLocals.get(Constants.USER_TOKEN);
            return account.getUserId();
        }
        LOGGER.info("get user sessiom from threadlocal is null ...");
        return null;
    }
}
